import React, { useCallback, useEffect, useState, useMemo } from 'react'
import {
  Form,
  Input,
  Button,
  Cascader,
  Space,
  Table,
  Tag,
  Popconfirm,
} from 'antd'
import * as XLSX from 'xlsx'
import { getDepartments } from 'api/department'
import { getDoctors, removeDoctor } from 'api/doctor'

export default function Doctor({history}) {
  // 用于绑定关联的表单实例
  const [form] = Form.useForm()

  // 状态数据
  const [departments, setDepartments] = useState([])
  const [doctors, setDoctors] = useState([])
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)

  // 根据条件分页查询医生列表数据，复用该函数
  const getDoctorList = useCallback(async({page, pageSize, departmentId, name} = {}) => {
    // 查询医生
    const {list, page: _page, pageSize: _pageSize, total} = await getDoctors({page, pageSize, departmentId, name})
    setDoctors(list)
    setPage(_page)
    setPageSize(_pageSize)
    setTotal(total)
  }, [])

  // 查询科室数据
  useEffect(() => {
    const fn = async() => {
      // getDepartments()
      //   .then(console.log)
      //   .catch(console.log)

      try {
        // try 语句块中放置可能会出现异常的代码
        const {list} = await getDepartments()
        setDepartments(list)
      } catch (error) {
        // catch 语句块中是出现异常后，解决异常问题的代码
        console.log('异常：', error)
      } finally {
        // finally 语句块是无论是否出现异常，最终都会执行的代码
      }
    }
    fn()
  }, [])

  // 查询医生数据
  useEffect(() => {
    getDoctorList({page, pageSize})
  }, [])

  // 查询表单验证成功提交
  const onSearch = useCallback(async values => {
    // 科室 id
    const departmentId = values.department?.pop()
    // 医生姓名
    const name = values.name
    // 查询医生
    getDoctorList({page, pageSize, departmentId, name})
  }, [])

  // 分页查找医生列表数据
  const listDoctor = (page, pageSize) => {
    getDoctorList({page, pageSize})
  }

  // 确认删除医生
  const doctorConfirm = async id => {
    // 删除
    await removeDoctor(id)
    // 删除后再查询一次当前页数据
    let _page = page
    if (doctors.length === 1) {
      _page -= 1
    } else if (_page <= 1) {
      _page = 1
    }
    getDoctorList()
  }

  // 跳转到编辑医生页面
  const jumpToEdit = useCallback(id => (
    history.push(`/hospital/doctor/edit?${typeof id === 'object' ? '' : ('id=' + id)}`)
  ), [])

  // 表格中列的定义
  const columns = useMemo(() => [
    {
      title: '医生姓名', // 列头显示文本
      dataIndex: 'name', // 数据项中当前列对应的属性名
      key: 'name', // 这是 React 渲染时需要的 key
      render: (text, record, index) => <a>{text}</a>, // 生成复杂数据的渲染函数
    },
    {
      title: '头像',
      dataIndex: 'avatarUrl',
      render: text =>  <img src={text ? text : 'https://joeschmoe.io/api/v1/random'} style={{width: 32}} alt="" />,
    },
    {
      title: '院区',
      dataIndex: 'district',
      render: text => <span>{text?.name}</span>,
    },
    {
      title: '职称',
      dataIndex: 'job',
      render: text => <span>{text?.name}</span>,
    },
    {
      title: '科室',
      dataIndex: 'department',
      render: text => <span>{text?.name}</span>,
    },
    {
      title: '标签',
      dataIndex: 'tags',
    },
    {
      title: '简介',
      dataIndex: 'introduction',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button onClick={jumpToEdit.bind(null, record.id)}>修改</Button>
          <Popconfirm
            placement="topRight"
            title="是否删除当前医生信息"
            onConfirm={doctorConfirm.bind(null, record.id)}
            okText="是"
            cancelText="否"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ], [])

  // 导出 excel 文件
  const exportFile = () => {
    // 将当前查询出的医生信息转换为待导出的数据结构
    // 待导出的数据结构应该是一个二维数组（数组的元素是数组）
    const header = doctors.length > 0 && Object.keys(doctors[0])
    const data = [
      header,
      ...doctors.map(doctor => {
        doctor.department = doctor.department.name
        doctor.district = doctor.district.name
        doctor.job = doctor.job.name

        return Object.values(doctor)
      }),
    ]

    // 将待导出数据转换为工作表的结构
    const ws = XLSX.utils.aoa_to_sheet(data)
    // 创建新工作簿对象
    const wb = XLSX.utils.book_new()
    // 在工作簿中追加工作表
    XLSX.utils.book_append_sheet(wb, ws, '医生信息')

    // 将内存中工作簿内容写入文件
    XLSX.writeFile(wb, `医生信息-${new Date().toISOString()}.xlsx`)
  }

  return (
    <div>
      {/* 查询表单 */}
      <Form form={form} layout="inline" onFinish={onSearch}>
        <Form.Item name="department">
          <Cascader
            placeholder="请选择科室"
            options={departments}
            fieldNames={{
              label: 'name',
              value: 'id',
              children: 'children',
            }}
          />
        </Form.Item>
        <Form.Item name="name">
          <Input placeholder="请输入医生姓名" />
        </Form.Item>
        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
          >
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={jumpToEdit}>新增医生信息</Button>
            <Button onClick={exportFile}>导出</Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 医生表格数据 */}
      <Table
        columns={columns}
        dataSource={doctors}
        rowKey="id"
        rowSelection={{
          type: 'checkbox',
        }}
        pagination={{
          position: ['bottomRight'],
          current: page,
          pageSize,
          pageSizeOptions: [1, 2, 5, 10],
          showSizeChanger: true,
          showQuickJumper: true,
          total,
          onChange: listDoctor,
        }}
      />
    </div>
  )
}
